package m.system.task;

import m.system.SystemTaskRun;
import m.system.cache.run.CacheHostTask;
import m.system.util.AnnotationUtil;
import m.system.util.ClassUtil;
import m.system.util.StringUtil;
import m.system.util.SystemUtil;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.List;
import java.util.Map;

public class TaskUtil {
	private static Scheduler scheduler;
	public static void initTask(List<String[]> list) throws SchedulerException, ClassNotFoundException {
		SchedulerFactory sFactory = new StdSchedulerFactory();
		scheduler = sFactory.getScheduler();
		JobDetail job;
		//初始化缓存定时器
		job=JobBuilder.newJob(CacheHostTask.class).build();//每分钟执行
		job.getJobDataMap().put("method", "run");
		scheduler.scheduleJob(job,TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule("1 * * * * ?")).build());
		//初始化系统定时器
		job=JobBuilder.newJob(SystemTask.class).build();//每天执行
		job.getJobDataMap().put("method", "run");
		scheduler.scheduleJob(job,TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 * * ?")).build());
		for(String[] strs : list){
			SystemUtil.printlnIf(true,strs[0],"--",strs[1]);
			Class<? extends SystemTaskRun> runClass=ClassUtil.getClass(SystemTaskRun.class,strs[0].trim());
			if(!StringUtil.isSpace(strs[1].trim())) {
				job=JobBuilder.newJob(runClass).build();
				job.getJobDataMap().put("method", "run");
				scheduler.scheduleJob(job,TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(strs[1].trim())).build());
			}
			Map<String,TaskRunMeta> map=AnnotationUtil.getAnnotationMap4Method(TaskRunMeta.class, runClass);
			for(String method : map.keySet()) {
				String cron=map.get(method).cron().trim();
				if(!StringUtil.isSpace(cron)) {
					job=JobBuilder.newJob(runClass).build();
					job.getJobDataMap().put("method", method);
					scheduler.scheduleJob(job,TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(cron)).build());
				}
			}
		}
		scheduler.start();
		SystemUtil.printlnIf(true,"定时任务已初始化完毕!");
	}
	public static void closeTask() {
		try {
			if(null!=scheduler) {
				scheduler.shutdown(true);
				SystemUtil.printlnIf(true,"定时任务已关闭!");
			}
		} catch (SchedulerException e) {
			SystemUtil.printlnIf(true,"定时任务关闭失败!");
			e.printStackTrace();
		}
	}
	
}
